package com.itheima.tlias.aspect;


import com.alibaba.fastjson.JSONObject;
import com.itheima.tlias.entity.Emp;
import com.itheima.tlias.entity.OperateLog;
import com.itheima.tlias.mapper.EmpMapper;
import com.itheima.tlias.mapper.OperateLogMapper;
import com.itheima.tlias.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @Aspect 标识切面类
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Resource
    OperateLogMapper logMapper;

    @Resource
    HttpServletRequest request;

    @Resource
    EmpMapper empMapper;

    @Around("@annotation(com.itheima.tlias.annotation.Log)")
    public Object insertLog(ProceedingJoinPoint joinPoint) {
        //执行父类方法
        try {
            long start = System.currentTimeMillis();
            Object proceed = joinPoint.proceed();
            long end = System.currentTimeMillis() - start;
            //获取登录人的id
            String token = request.getHeader("token");
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
            log.info("操作{}方法插入日志", joinPoint.getSignature().getName());
            OperateLog build = OperateLog.builder().className(joinPoint.getTarget().getClass().getName())
                    .methodName(joinPoint.getSignature().getName())
                    .methodParams(Arrays.toString(joinPoint.getArgs()))
                    .operateTime(LocalDateTime.now())
                    .returnValue(proceed.toString())
                    .costTime((int) end)
                    .operateEmpId(String.valueOf(emp.getId())).build();
            int i = logMapper.insertLog(build);
            log.info("插入日志{}", i);
            return proceed;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

}
